package com.ysd.lis.service.eq.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.WkFolder;
import com.ysd.lis.entity.eq.*;
import com.ysd.lis.mapper.eq.*;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.eq.EqRepairDto;
import com.ysd.lis.request.eq.EqRepairParam;
import com.ysd.lis.request.eq.RepairPersonVo;
import com.ysd.lis.request.eq.RepairTjfxVo;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.WkFolderService;
import com.ysd.lis.service.eq.EqRepairOrderService;
import com.ysd.lis.service.eq.EqRepairPersonService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备管理-设备类型 服务实现类
 * </p>
 *
 * @author prs
 * @since 2024-08-22
 */
@Service
public class EqRepairOrderServiceImpl extends ServiceImpl<EqRepairOrderMapper, EqRepairOrder> implements EqRepairOrderService {

    @Autowired
    EqRepairOrderMapper eqRepairOrderMapper;
    @Autowired
    EqRepairPersonService eqRepairPersonService;
    @Autowired
    EqRepairPersonMapper eqRepairPersonMapper;
    @Autowired
    EqRepairRecordMapper eqRepairRecordMapper;
    @Autowired
    SysRuleSetService sysRuleSetService;//编码规则服务
    @Autowired
    EqRepairPlanMapper eqRepairPlanMapper;
    @Autowired
    EqFaultRepairMapper eqFaultRepairMapper;
    @Override
    public Result findRepairOrderPageList(CommonPageDto pageParam) {
        Page<EqRepairOrder> page = new Page<>();
        page.setCurrent(pageParam.getPageIndex());
        page.setSize(pageParam.getPageSize());
        MPJLambdaWrapper<EqRepairOrder> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqRepairOrder.class)
                .selectAs("eq", EqEquipment::getEquiptName,EqRepairOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqRepairOrder::getSpecification)
                .selectAs("et",EqFaultType::getFaultTypeName,EqRepairOrder::getFaultTypeName)

                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqRepairOrder::getEquiptId)
                .leftJoin(EqFaultType.class,"et",p->p.eq(EqFaultType::getFaultTypeCode,EqRepairOrder::getFaultType).eq(EqFaultType::getDelFlag,0) )

                .eq(EqRepairOrder::getDelFlag, 0);
        if (StringUtils.isNotBlank(pageParam.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(EqRepairOrder::getRepairNo, pageParam.getSeachValue())
                    .or().like(EqRepairOrder::getEquiptCode, pageParam.getSeachValue()));
        }
        if(ToolsUtils.isNotEmpty(pageParam.getPlanId())){
            lambdaQueryWrapper.eq(EqRepairOrder::getPlanId,pageParam.getPlanId());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getFaultId())){
            lambdaQueryWrapper.eq(EqRepairOrder::getFaultId,pageParam.getFaultId());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getStatus())){
            lambdaQueryWrapper.eq(EqRepairOrder::getRepairStatus,pageParam.getStatus());
        }
        if(ToolsUtils.isNotEmpty(pageParam.getEquiptId())){
            lambdaQueryWrapper.eq(EqRepairOrder::getEquiptId,pageParam.getEquiptId());
        }
        lambdaQueryWrapper.orderByDesc(EqRepairOrder::getCreateTime);
        Page<EqRepairOrder> orderPage = eqRepairOrderMapper.selectPage(page, lambdaQueryWrapper);
        return Result.succ(1, "查询成功", orderPage);
    }

    @Override
    public Result addRepairOrder(EqRepairOrder eqRepairOrder) {
        String a = sysRuleSetService.createRuleCodeList("eqRepairNo", 1).get(0);
        eqRepairOrder.setRepairNo(a);
        if(ToolsUtils.isNotEmpty(eqRepairOrder.getPlanId())){
            String repairStatus = eqRepairOrder.getRepairStatus();
            if(repairStatus.equals("25")){
                eqRepairOrder.setRepairStatus("20");
            }
        }
        boolean save = this.save(eqRepairOrder);
        if (save) {
            String planId = eqRepairOrder.getPlanId();
            if(ToolsUtils.isNotEmpty(planId)){
                EqRepairPlan plan = eqRepairPlanMapper.selectById(planId);
                String repairStatus = eqRepairOrder.getRepairStatus();
                if(repairStatus.equals("25")){
                    plan.setPlanStatus("15");
                }else {
                    plan.setPlanStatus("10");

                }
                eqRepairPlanMapper.updateById(plan);
            }
            //person
            List<EqRepairPerson> repairPersonList = eqRepairOrder.getRepairPersonList();
            for(EqRepairPerson repairPerson : repairPersonList){
                repairPerson.setRepairId(eqRepairOrder.getId());
                repairPerson.setRepairNo(eqRepairOrder.getRepairNo());
            }
            boolean b = eqRepairPersonService.saveBatch(repairPersonList);
            //新增操作记录
            EqRepairRecord repairRecord = new EqRepairRecord();
            repairRecord.setRepairId(eqRepairOrder.getId());
            repairRecord.setRepairNo(eqRepairOrder.getRepairNo());
            repairRecord.setOperateDate(new Timestamp(new Date().getTime()));
            SysUser sysUser = RedisUserManager.getUser();
            repairRecord.setOperatorId(sysUser.getId());
            repairRecord.setOperator(sysUser.getRealname());
            repairRecord.setOperate("维修");
            repairRecord.setOperateResult("创建快速工单");
            eqRepairRecordMapper.insert(repairRecord);

            //创建文件夹
            List<Map<String, Object>> fileFolderList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("eqFileFolder").getData();
            List<WkFolder> sbList = wkFolderService.list(new LambdaQueryWrapper<WkFolder>().eq(WkFolder::getCode, "eqRepairOrder").eq(WkFolder::getDelFlag, 0));
            if (CollectionUtil.isNotEmpty(sbList)) {
                WkFolder sbFolder = sbList.get(0);
                String[] split = sbFolder.getFileFolder().split(",");
                WkFolder wkFolder = new WkFolder();
                wkFolder.setCode(a);
                wkFolder.setName(a);
                wkFolder.setPid(sbFolder.getId());
                wkFolder.setGrade(0);
                wkFolderService.save(wkFolder);
                if (split.length > 0) {
                    for (String fileFolder : split) {
                        for (Map<String, Object> map : fileFolderList) {
                            if (fileFolder.equals(map.get("code"))) {
                                WkFolder wkFolder1 = new WkFolder();
                                wkFolder1.setCode(a+fileFolder);
                                wkFolder1.setName(map.get("name").toString());
                                wkFolder1.setPid(wkFolder.getId());
                                wkFolder1.setGrade(0);
                                wkFolderService.save(wkFolder1);
                            }
                        }
                    }
                }
            }

            return Result.succ(1, "添加成功", eqRepairOrder);

        } else {
            return Result.fail("添加失败");
        }
    }
    @Autowired
    WkFolderService wkFolderService;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Override
    public Result updatRepairOrder(EqRepairOrder eqRepairOrder) {
        if(eqRepairOrder.getRepairStatus().equals("25")){
            eqRepairOrder.setRepairStatus("20");
        }
        boolean save = this.updateById(eqRepairOrder);
        if (save) {

            String planId = eqRepairOrder.getPlanId();
            if(ToolsUtils.isNotEmpty(planId)&&eqRepairOrder.getRepairStatus().equals("25")){
                EqRepairPlan plan = eqRepairPlanMapper.selectById(planId);
                plan.setPlanStatus("15");
                eqRepairPlanMapper.updateById(plan);
            }
            //报修
            String faultId = eqRepairOrder.getFaultId();
            if(ToolsUtils.isNotEmpty(faultId)){
                EqFaultRepair faultRepair = eqFaultRepairMapper.selectById(faultId);
                if(eqRepairOrder.getRepairStatus().equals("20")){
                    //待验证
                    faultRepair.setFaultStatus("15");
                }else {
                    faultRepair.setFaultStatus("10");
                }
                eqFaultRepairMapper.updateById(faultRepair);
            }
            //person
            //先删除 再添加或修改
            LambdaQueryWrapper<EqRepairPerson> delPersonWrapper = new LambdaQueryWrapper<>();
            delPersonWrapper.eq(EqRepairPerson::getRepairId,eqRepairOrder.getId());
            eqRepairPersonMapper.delete(delPersonWrapper);
            List<EqRepairPerson> eqRepairPersonList = eqRepairOrder.getRepairPersonList();
            boolean b = eqRepairPersonService.saveBatch(eqRepairPersonList);

            //新增操作记录
            EqRepairRecord repairRecord = new EqRepairRecord();
            repairRecord.setRepairId(eqRepairOrder.getId());
            repairRecord.setRepairNo(eqRepairOrder.getRepairNo());
            repairRecord.setOperateDate(new Timestamp(new Date().getTime()));
            SysUser sysUser = RedisUserManager.getUser();
            repairRecord.setOperatorId(sysUser.getId());
            repairRecord.setOperator(sysUser.getRealname());
            repairRecord.setOperate("维修");
            repairRecord.setOperateResult("执行维修");
            eqRepairRecordMapper.insert(repairRecord);

            return Result.succ(1, "编辑成功", eqRepairOrder);

        }else {
            return Result.fail("编辑失败");
        }
    }

    @Override
    public Result batchDeleteRepairOrderList(EqRepairDto dto) {
        List<EqRepairOrder> eqRepairOrderList = dto.getEqRepairOrderList();
        List<String> ids = eqRepairOrderList.stream().map(EqRepairOrder::getId).collect(Collectors.toList());
        boolean b = this.removeByIds(ids);
        if(b){
            //person
            LambdaUpdateWrapper<EqRepairPerson> deleteTableWrapper = new LambdaUpdateWrapper<>();
            deleteTableWrapper.in(EqRepairPerson::getRepairId, ids);
            eqRepairPersonMapper.delete(deleteTableWrapper);
            return Result.succ(1, "删除成功", null);
        }else {
            return Result.fail(400,"删除失败","");
        }
    }

    @Override
    public Result findEqRepairOrderById(EqRepairOrder eqRepairOrder) {
        String id = eqRepairOrder.getId();

        MPJLambdaWrapper<EqRepairOrder> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(EqRepairOrder.class)
                .selectAs("eq",EqEquipment::getEquiptName,EqRepairOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqRepairOrder::getSpecification)
                .selectAs("et",EqFaultType::getFaultTypeName,EqRepairOrder::getFaultTypeName)

                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqRepairOrder::getEquiptId)
                .leftJoin(EqFaultType.class,"et",p->p.eq(EqFaultType::getFaultTypeCode,EqRepairOrder::getFaultType).eq(EqFaultType::getDelFlag,0) )

                .eq(EqRepairOrder::getId,id)
                .eq(EqRepairOrder::getDelFlag, 0);
        EqRepairOrder repairOrder = eqRepairOrderMapper.selectOne(lambdaQueryWrapper);

        //获取person
        MPJLambdaWrapper<EqRepairPerson> queryTableWrapper = new MPJLambdaWrapper<>();
        queryTableWrapper.selectAll(EqRepairPerson.class)
                .eq(EqRepairPerson::getRepairId,id)
                .eq(EqRepairPerson::getDelFlag,0);
        List<EqRepairPerson> personList = eqRepairPersonMapper.selectList(queryTableWrapper);
        repairOrder.setRepairPersonList(personList);
        //获取detail

        MPJLambdaWrapper<EqRepairRecord> queryTableWrapper1 = new MPJLambdaWrapper<>();
        queryTableWrapper1.selectAll(EqRepairRecord.class)
                .eq(EqRepairRecord::getRepairId,id)
                .eq(EqRepairRecord::getDelFlag,0);
        List<EqRepairRecord> detailList = eqRepairRecordMapper.selectList(queryTableWrapper1);
        repairOrder.setRepairRecordList(detailList);

        return Result.succ(1, "查询成功", repairOrder);
    }

    @Override
    public Result verifyRepairOrder(EqRepairDto dto) {
        List<EqRepairOrder> eqRepairOrderList = dto.getEqRepairOrderList();
        for(EqRepairOrder eqRepairOrder : eqRepairOrderList){
            eqRepairOrder.setRepairStatus(dto.getRepairStatus());
        }
        boolean b = this.updateBatchById(eqRepairOrderList);
        if(b){
            for(EqRepairOrder eqRepairOrder: eqRepairOrderList){

                String planId = eqRepairOrder.getPlanId();
                if(ToolsUtils.isNotEmpty(planId)&&eqRepairOrder.getRepairStatus().equals("25")){
                    EqRepairPlan plan = eqRepairPlanMapper.selectById(planId);
                    plan.setPlanStatus("15");
                    eqRepairPlanMapper.updateById(plan);
                }
                String faultId = eqRepairOrder.getFaultId();
                if(ToolsUtils.isNotEmpty(faultId)){
                    if(eqRepairOrder.getRepairStatus().equals("25")){
                        EqFaultRepair faultRepair = eqFaultRepairMapper.selectById(faultId);
                        faultRepair.setFaultStatus("20");
                        eqFaultRepairMapper.updateById(faultRepair);
                    }
                }

                //新增操作记录
                EqRepairRecord repairRecord = new EqRepairRecord();
                repairRecord.setRepairId(eqRepairOrder.getId());
                repairRecord.setRepairNo(eqRepairOrder.getRepairNo());
                repairRecord.setOperateDate(new Timestamp(new Date().getTime()));
                SysUser sysUser = RedisUserManager.getUser();
                repairRecord.setOperatorId(sysUser.getId());
                repairRecord.setOperator(sysUser.getRealname());
                repairRecord.setOperate("验证");
                if(eqRepairOrder.getRepairStatus().equals("25")){
                    repairRecord.setOperateResult("故障已修复");
                }else if(eqRepairOrder.getRepairStatus().equals("15")){
                    repairRecord.setOperateResult("故障未修复");
                }else {
                    repairRecord.setOperateResult("故障未修复");
                }
                eqRepairRecordMapper.insert(repairRecord);
            }
            return Result.succ(1, "成功", null);
        }else {
            return Result.fail(400,"失败","");
        }
    }

    @Autowired
    EqEquiptTypeMapper eqEquiptTypeMapper;
    @Autowired
    EqEquipmentMapper eqEquipmentMapper;
    @Override
    public Result getRepairTjfxByEqType(EqRepairParam param) {
        //查出所有的设备分类
        LambdaQueryWrapper<EqEquiptType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EqEquiptType::getDelFlag, 0);
        List<EqEquiptType> equiptTypeList = eqEquiptTypeMapper.selectList(lambdaQueryWrapper);
        //查出顶端分类
        List<EqEquiptType> parentTypeList = equiptTypeList.stream().filter(a -> ToolsUtils.isEmpty(a.getParentId())).collect(Collectors.toList());

        //查出所有的设备
        MPJLambdaWrapper<EqEquipment> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqEquipment.class)
                .eq(EqEquipment::getDelFlag, 0);

        List<EqEquipment> eqEquipmentList = eqEquipmentMapper.selectList(eqMPJLambdaWrapper);

        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();

        MPJLambdaWrapper<EqRepairOrder> reMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reMPJLambdaWrapper.selectAll(EqRepairOrder.class)
                .eq(EqRepairOrder::getDelFlag, 0);
        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }


        List<EqRepairOrder> eqRepairOrderList = eqRepairOrderMapper.selectList(reMPJLambdaWrapper);


        List<RepairTjfxVo> voList = new ArrayList<>();
        for(EqEquiptType parentType : parentTypeList){
            RepairTjfxVo vo = new RepairTjfxVo();
            vo.setEquiptTypeCode(parentType.getEquiptTypeCode());
            vo.setEquiptTypeId(parentType.getId());
            vo.setEquiptTypeName(parentType.getEquiptTypeName());
            List<EqEquiptType> returnList = new ArrayList<>();
            returnList.add(parentType);
            //取出下边所有的分类
            getChild(parentType,equiptTypeList,returnList);
            List<String> equiptTypeCodeList = returnList.stream().map(EqEquiptType::getEquiptTypeCode).collect(Collectors.toList());

            //设备分类下所有的设备
            List<EqEquipment> equipmentList = eqEquipmentList.stream().filter(a -> equiptTypeCodeList.contains(a.getEquiptTypeCode())).collect(Collectors.toList());

            //总台数
            vo.setEquiptCnt(equipmentList.size());

            List<String> equiptCodeList = equipmentList.stream().map(EqEquipment::getEquiptCode).collect(Collectors.toList());
            List<EqRepairOrder> repairOrderList = eqRepairOrderList.stream().filter(a -> equiptCodeList.contains(a.getEquiptCode())).collect(Collectors.toList());
            //故障台数
            vo.setRepairEqCnt(repairOrderList.stream().map(EqRepairOrder::getEquiptId).distinct().collect(Collectors.toList()).size());
            //总故障次数
            vo.setRepairCnt(repairOrderList.size());
            //已维修故障
            List<EqRepairOrder> collect = repairOrderList.stream().filter(a -> a.getRepairStatus().equals("25")).collect(Collectors.toList());

            vo.setRepairedCnt(collect.size());
            if(ToolsUtils.isNotEmpty(collect)){
                //维修用时
                vo.setWorkHours(collect.stream().filter(a->ToolsUtils.isNotEmpty(a.getWorkHours())).mapToInt(EqRepairOrder::getWorkHours).sum());
                //维修费用
                vo.setRepairFee(collect.stream().filter(a->ToolsUtils.isNotEmpty(a.getRepairFee())).mapToInt(EqRepairOrder::getRepairFee).sum());
            }else {
                vo.setWorkHours(0);
                vo.setRepairFee(0);
            }
            voList.add(vo);
        }
        return Result.succ(voList);
    }

    @Override
    public Result getRepairPersonWorkHours(EqRepairParam param) {
        MPJLambdaWrapper<EqRepairPerson> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqRepairPerson.class)
                .innerJoin(EqRepairOrder.class,"re",p->p.eq(EqRepairOrder::getId,EqRepairPerson::getRepairId).eq(EqRepairOrder::getRepairStatus,"25").eq(EqRepairOrder::getDelFlag,0))
                .isNotNull(EqRepairPerson::getPersonId)
                .ne(EqRepairPerson::getPersonId,"")
                .eq(EqRepairPerson::getDelFlag,0);
        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();
        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            eqMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                eqMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }
        List<EqRepairPerson> eqRepairPeopleList = eqRepairPersonMapper.selectList(eqMPJLambdaWrapper);
        Map<List<String>, List<EqRepairPerson>> listMap = eqRepairPeopleList.stream().collect(Collectors.groupingBy(s -> Arrays.asList(s.getPersonId(),s.getPerson())));

        List<RepairPersonVo> voList = new ArrayList<>();

        for(List<String> list : listMap.keySet()){
            RepairPersonVo vo = new RepairPersonVo();
            String personId = list.get(0);
            String person = list.get(1);
            List<EqRepairPerson> eqRepairPeoples = listMap.get(list);
            vo.setPersonId(personId);
            vo.setPerson(person);
            vo.setRepairCnt(eqRepairPeoples.size());
            vo.setWorkHours(eqRepairPeoples.stream().filter(a->ToolsUtils.isNotEmpty(a.getWorkHours())).mapToInt(EqRepairPerson::getWorkHours).sum());
            vo.setWorkHoursAvg((eqRepairPeoples.stream().filter(a->ToolsUtils.isNotEmpty(a.getWorkHours())).mapToInt(EqRepairPerson::getWorkHours).sum())/eqRepairPeoples.size());

            voList.add(vo);
        }

        return Result.succ(voList);
    }

    @Override
    public Result getRepairTjfxByEquipt(EqRepairParam param) {

        //查出所有的设备分类
        LambdaQueryWrapper<EqEquiptType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EqEquiptType::getDelFlag, 0);
        List<EqEquiptType> equiptTypeList = eqEquiptTypeMapper.selectList(lambdaQueryWrapper);

        //查出所有的设备
        MPJLambdaWrapper<EqEquipment> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqEquipment.class)
                .eq(EqEquipment::getDelFlag, 0);

        List<EqEquipment> eqEquipments = eqEquipmentMapper.selectList(eqMPJLambdaWrapper);
        List<EqEquipment> equipmentList = new ArrayList<>();

        if(ToolsUtils.isNotEmpty(param.getEquiptTypeCode())){
            EqEquiptType eqEquiptType = equiptTypeList.stream().filter(a->a.getEquiptTypeCode().equals(param.getEquiptTypeCode())).findFirst().get();
            List<EqEquiptType> returnList = new ArrayList<>();
            returnList.add(eqEquiptType);
            //取出下边所有的分类
            getChild(eqEquiptType,equiptTypeList,returnList);
            List<String> equiptTypeCodeList = returnList.stream().map(EqEquiptType::getEquiptTypeCode).collect(Collectors.toList());
            //设备分类下所有的设备
             equipmentList = eqEquipments.stream().filter(a -> equiptTypeCodeList.contains(a.getEquiptTypeCode())).collect(Collectors.toList());
        }else {
            equipmentList.addAll(eqEquipments);
        }


        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();
        MPJLambdaWrapper<EqRepairOrder> reMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reMPJLambdaWrapper.selectAll(EqRepairOrder.class)
                .eq(EqRepairOrder::getDelFlag, 0);
        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }

        List<EqRepairOrder> eqRepairOrderList = eqRepairOrderMapper.selectList(reMPJLambdaWrapper);
        List<RepairTjfxVo> voList = new ArrayList<>();

        for(EqEquipment eqEquipment : equipmentList){
            RepairTjfxVo vo = new RepairTjfxVo();
            vo.setEquiptCode(eqEquipment.getEquiptCode());
            vo.setEquiptId(eqEquipment.getId());
            vo.setEquiptName(eqEquipment.getEquiptName());
            vo.setSpecification(eqEquipment.getSpecification());
            vo.setEquiptTypeCode(eqEquipment.getEquiptTypeCode());
            vo.setEquiptTypeName(eqEquipment.getEquiptTypeName());
            List<EqRepairOrder> repairOrderList = eqRepairOrderList.stream().filter(a -> eqEquipment.getEquiptCode().equals(a.getEquiptCode())).collect(Collectors.toList());

            //总故障次数
            vo.setRepairCnt(repairOrderList.size());
            //已维修故障
            List<EqRepairOrder> collect = repairOrderList.stream().filter(a -> a.getRepairStatus().equals("25")).collect(Collectors.toList());
            vo.setRepairedCnt(collect.size());
            if(ToolsUtils.isNotEmpty(collect)){
                //维修用时
                vo.setWorkHours(collect.stream().filter(a->ToolsUtils.isNotEmpty(a.getWorkHours())).mapToInt(EqRepairOrder::getWorkHours).sum());
                //维修费用
                vo.setRepairFee(collect.stream().filter(a->ToolsUtils.isNotEmpty(a.getRepairFee())).mapToInt(EqRepairOrder::getRepairFee).sum());
            }else {
                vo.setWorkHours(0);
                vo.setRepairFee(0);
            }
            voList.add(vo);
        }
        return Result.succ(voList);
    }

    @Override
    public Result getRepairDetailByPerson(EqRepairParam param) {
        String personId = param.getPersonId();
        MPJLambdaWrapper<EqRepairOrder> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqRepairOrder.class)
                .selectAs("eq", EqEquipment::getEquiptName,EqRepairOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqRepairOrder::getSpecification)
                .selectAs("et",EqFaultType::getFaultTypeName,EqRepairOrder::getFaultTypeName)
                .innerJoin(EqRepairPerson.class,"re",p->p.eq(EqRepairPerson::getRepairId,EqRepairOrder::getId).eq(EqRepairPerson::getPersonId,personId).isNotNull(EqRepairPerson::getPersonId).ne(EqRepairPerson::getPersonId,"").eq(EqRepairPerson::getDelFlag,0))
                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqRepairOrder::getEquiptId)
                .leftJoin(EqFaultType.class,"et",p->p.eq(EqFaultType::getFaultTypeCode,EqRepairOrder::getFaultType).eq(EqFaultType::getDelFlag,0) )

                .eq(EqRepairOrder::getRepairStatus,"25")
                .eq(EqRepairOrder::getDelFlag,0);

        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();
        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            eqMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                eqMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }
        List<EqRepairOrder> eqRepairOrderList = eqRepairOrderMapper.selectList(eqMPJLambdaWrapper);

        return Result.succ(eqRepairOrderList);
    }

    @Override
    public Result getRepairDetailByEqType(EqRepairParam param) {
        //查出所有的设备分类
        LambdaQueryWrapper<EqEquiptType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EqEquiptType::getDelFlag, 0);
        List<EqEquiptType> equiptTypeList = eqEquiptTypeMapper.selectList(lambdaQueryWrapper);

        //查出所有的设备
        MPJLambdaWrapper<EqEquipment> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqEquipment.class)
                .eq(EqEquipment::getDelFlag, 0);
        List<EqEquipment> eqEquipments = eqEquipmentMapper.selectList(eqMPJLambdaWrapper);
        List<EqEquipment> equipmentList = new ArrayList<>();

        if(ToolsUtils.isNotEmpty(param.getEquiptTypeCode())){
            EqEquiptType eqEquiptType = equiptTypeList.stream().filter(a->a.getEquiptTypeCode().equals(param.getEquiptTypeCode())).findFirst().get();
            List<EqEquiptType> returnList = new ArrayList<>();
            returnList.add(eqEquiptType);
            //取出下边所有的分类
            getChild(eqEquiptType,equiptTypeList,returnList);
            List<String> equiptTypeCodeList = returnList.stream().map(EqEquiptType::getEquiptTypeCode).collect(Collectors.toList());
            //设备分类下所有的设备
            equipmentList = eqEquipments.stream().filter(a -> equiptTypeCodeList.contains(a.getEquiptTypeCode())).collect(Collectors.toList());
        }else {
            equipmentList.addAll(eqEquipments);
        }

        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();
        MPJLambdaWrapper<EqRepairOrder> reMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reMPJLambdaWrapper.selectAll(EqRepairOrder.class)
                .selectAs("eq", EqEquipment::getEquiptName,EqRepairOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqRepairOrder::getSpecification)
                .selectAs("et",EqFaultType::getFaultTypeName,EqRepairOrder::getFaultTypeName)

                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqRepairOrder::getEquiptId)
                .leftJoin(EqFaultType.class,"et",p->p.eq(EqFaultType::getFaultTypeCode,EqRepairOrder::getFaultType).eq(EqFaultType::getDelFlag,0) )

                .eq(EqRepairOrder::getDelFlag, 0)
                .in(EqRepairOrder::getEquiptId,equipmentList.stream().map(EqEquipment::getId).collect(Collectors.toList()));
        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }

        List<EqRepairOrder> eqRepairOrderList = eqRepairOrderMapper.selectList(reMPJLambdaWrapper);


        return Result.succ(eqRepairOrderList);
    }

    @Override
    public Result getRepairDetailByEquipt(EqRepairParam param) {
        //查出所有的设备
        MPJLambdaWrapper<EqEquipment> eqMPJLambdaWrapper = new MPJLambdaWrapper<>();
        eqMPJLambdaWrapper.selectAll(EqEquipment.class)
                .eq(EqEquipment::getId,param.getEquiptId())
                .eq(EqEquipment::getDelFlag, 0);
        List<EqEquipment> equipmentList = eqEquipmentMapper.selectList(eqMPJLambdaWrapper);
        //查出所有的设备维修工单
        String monthType = param.getMonthType();
        String paramMonth = param.getMonth();
        MPJLambdaWrapper<EqRepairOrder> reMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reMPJLambdaWrapper.selectAll(EqRepairOrder.class)
                .selectAs("eq", EqEquipment::getEquiptName,EqRepairOrder::getEquiptName)
                .selectAs("eq",EqEquipment::getSpecification,EqRepairOrder::getSpecification)
                .selectAs("et",EqFaultType::getFaultTypeName,EqRepairOrder::getFaultTypeName)

                .leftJoin(EqEquipment.class,"eq",EqEquipment::getId,EqRepairOrder::getEquiptId)
                .leftJoin(EqFaultType.class,"et",p->p.eq(EqFaultType::getFaultTypeCode,EqRepairOrder::getFaultType).eq(EqFaultType::getDelFlag,0) )

                .eq(EqRepairOrder::getDelFlag, 0)
                .in(EqRepairOrder::getEquiptId,equipmentList.stream().map(EqEquipment::getId).collect(Collectors.toList()));
        if(ToolsUtils.isNotEmpty(monthType)){
            Date today=null;
            if(monthType.equals("thisMonth")){
                //本月
                YearMonth currentYearMonth = YearMonth.now();
                int year = currentYearMonth.getYear();
                int month = currentYearMonth.getMonthValue();
                today = DateUtil.parse(year+"-"+month, "yyyy-MM");

            }else if(monthType.equals("lastMonth")){
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MONTH, -1);
                Date lastMonth = calendar.getTime();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
                String formattedDate = dateFormat.format(lastMonth);
                today = DateUtil.parse(formattedDate, "yyyy-MM");

            }
            reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                    .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
        }else {
            if(ToolsUtils.isNotEmpty(paramMonth)){
                Date today = DateUtil.parse(paramMonth, "yyyy-MM");
                reMPJLambdaWrapper.ge(EqRepairOrder::getCreateTime, DateUtil.beginOfMonth(today).toTimestamp())
                        .le(EqRepairOrder::getCreateTime, DateUtil.endOfMonth(today).toTimestamp());
            }
        }

        List<EqRepairOrder> eqRepairOrderList = eqRepairOrderMapper.selectList(reMPJLambdaWrapper);


        return Result.succ(eqRepairOrderList);
    }

    private void getChild(EqEquiptType m, List<EqEquiptType> folderList,List<EqEquiptType> returnList) {
        List<EqEquiptType> result = new ArrayList();
        for (EqEquiptType to : folderList) {
            if (ToolsUtils.isNotEmpty(to.getParentId())&&to.getParentId().equals(m.getId())) {
                result.add(to);
            }
        }

        for (EqEquiptType ma : result) {
            returnList.add(ma);
            getChild(ma, folderList,returnList);
        }

    }

}
